package com.ruoyi.gateway.service;

import com.ruoyi.gateway.domain.dto.DeviceMap;
import com.ruoyi.gateway.domain.TopicMap;
import com.ruoyi.gateway.domain.MessagePropertyMap;
import com.ruoyi.gateway.mapper.DeviceMapMapper;
import com.ruoyi.gateway.mapper.MessagePropertyMapMapper;
import com.ruoyi.gateway.mapper.TopicMapMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CacheService {
    private static final String DEVICE_MAP_KEY = "iot:device:map";
    private static final String TOPIC_MAP_KEY = "iot:topic:map";
    private static final String PROPERTY_MAP_KEY = "iot:property:map";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private DeviceMapMapper deviceMapMapper;

    @Autowired
    private TopicMapMapper topicMapMapper;

    @Autowired
    private MessagePropertyMapMapper messagePropertyMapMapper;

    @PostConstruct
    public void initCache() {
        loadDeviceMapCache();
        loadTopicMapCache();
        loadPropertyMapCache();
    }



    public void loadDeviceMapCache() {
        List<DeviceMap> deviceMaps = deviceMapMapper.selectDeviceMapList(null);
        Map<String, DeviceMap> cacheMap = deviceMaps.stream()
                .collect(Collectors.toMap(
                        dm -> buildDeviceKey(dm.getClientClientId(), dm.getClientDeviceIndex()),
                        Function.identity()
                ));
        redisTemplate.opsForHash().putAll(DEVICE_MAP_KEY, cacheMap);
    }

    private String buildDeviceKey(String clientId, String index) {
        return clientId + ":" + (index == null ? "" : index);
    }

    private void loadPropertyMapCache() {
        List<MessagePropertyMap> messagePropertyMaps = messagePropertyMapMapper.selectMessagePropertyMapList(null);
        Map<String, MessagePropertyMap> cacheMap = messagePropertyMaps.stream()
                .collect(Collectors.toMap(
                        dm -> dm.getPlatformPropertyPath(),
                        Function.identity()
                ));
        redisTemplate.opsForHash().putAll(PROPERTY_MAP_KEY, cacheMap);
    }

    private void loadTopicMapCache() {
        List<TopicMap> topicMaps = topicMapMapper.selectTopicMapList(null);
        Map<String, TopicMap> cacheMap = topicMaps.stream()
                .collect(Collectors.toMap(
                        dm -> dm.getDeviceTopicPattern(),
                        Function.identity()
                ));
        redisTemplate.opsForHash().putAll(TOPIC_MAP_KEY, cacheMap);
    }
}
